import "dotenv/config";
{{#if (eq runtime "node")}}
import { node } from "@elysiajs/node";
{{/if}}
import { Elysia } from "elysia";
import { cors } from "@elysiajs/cors";
{{#if (includes examples "ai")}}
import { google } from "@ai-sdk/google";
import { convertToModelMessages, streamText } from "ai";
{{/if}}
{{#if (eq api "trpc")}}
import { createContext } from "@{{projectName}}/api/context";
import { appRouter } from "@{{projectName}}/api/routers/index";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
{{/if}}
{{#if (eq api "orpc")}}
import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { OpenAPIReferencePlugin } from "@orpc/openapi/plugins";
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { RPCHandler } from "@orpc/server/fetch";
import { onError } from "@orpc/server";
import { appRouter } from "@{{projectName}}/api/routers/index";
import { createContext } from "@{{projectName}}/api/context";
{{/if}}
{{#if (eq auth "better-auth")}}
import { auth } from "@{{projectName}}/auth";
{{/if}}

{{#if (eq api "orpc")}}
const rpcHandler = new RPCHandler(appRouter, {
  interceptors: [
    onError((error) => {
      console.error(error);
    }),
  ],
});
const apiHandler = new OpenAPIHandler(appRouter, {
  plugins: [
    new OpenAPIReferencePlugin({
      schemaConverters: [new ZodToJsonSchemaConverter()],
    }),
  ],
  interceptors: [
    onError((error) => {
      console.error(error);
    }),
  ],
});
{{/if}}

{{#if (eq runtime "node")}}
const app = new Elysia({ adapter: node() })
{{else}}
const app = new Elysia()
{{/if}}
  .use(
    cors({
      origin: process.env.CORS_ORIGIN || "",
      methods: ["GET", "POST", "OPTIONS"],
      {{#if (eq auth "better-auth")}}
      allowedHeaders: ["Content-Type", "Authorization"],
      credentials: true,
      {{/if}}
    }),
  )
  {{#if (eq auth "better-auth")}}
  .all("/api/auth/*", async (context) => {
    const { request, status } = context;
    if (["POST", "GET"].includes(request.method)) {
      return auth.handler(request);
    }
    return status(405)
  })
  {{/if}}
{{#if (eq api "orpc")}}
  .all('/rpc*', async (context) => {
    const { response } = await rpcHandler.handle(context.request, {
      prefix: '/rpc',
      context: await createContext({ context })
    })
    return response ?? new Response('Not Found', { status: 404 })
  })
  .all('/api*', async (context) => {
    const { response } = await apiHandler.handle(context.request, {
      prefix: '/api-reference',
      context: await createContext({ context })
    })
    return response ?? new Response('Not Found', { status: 404 })
  })
{{/if}}
{{#if (eq api "trpc")}}
  .all("/trpc/*", async (context) => {
    const res = await fetchRequestHandler({
      endpoint: "/trpc",
      router: appRouter,
      req: context.request,
      createContext: () => createContext({ context }),
    });
    return res;
  })
{{/if}}
{{#if (includes examples "ai")}}
  .post("/ai", async (context) => {
    const body = await context.request.json();
    const uiMessages = body.messages || [];
    const result = streamText({
      model: google("gemini-2.5-flash"),
      messages: convertToModelMessages(uiMessages)
    });

    return result.toUIMessageStreamResponse();
  })
{{/if}}
  .get("/", () => "OK")
  .listen(3000, () => {
    console.log("Server is running on http://localhost:3000");
  });
